{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
        "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/ImageCollection/mosaicking.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/ImageCollection/mosaicking.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/ImageCollection/mosaicking.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Install Earth Engine API and geemap\n",
        "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
        "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n",
        "\n",
        "**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Installs geemap package\n",
        "import subprocess\n",
        "\n",
        "try:\n",
        "    import geemap\n",
        "except ImportError:\n",
        "    print('geemap package not installed. Installing ...')\n",
        "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n",
        "\n",
        "# Checks whether this notebook is running on Google Colab\n",
        "try:\n",
        "    import google.colab\n",
        "    import geemap.eefolium as geemap\n",
        "except:\n",
        "    import geemap\n",
        "\n",
        "# Authenticates and initializes Earth Engine\n",
        "import ee\n",
        "\n",
        "try:\n",
        "    ee.Initialize()\n",
        "except Exception as e:\n",
        "    ee.Authenticate()\n",
        "    ee.Initialize()  "
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Create an interactive map \n",
        "The default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map = geemap.Map(center=[40,-100], zoom=4)\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Add Earth Engine Python script "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Add Earth Engine dataset\n",
        "# Load three NAIP quarter quads in the same location, different times.\n",
        "naip2004_2012 = ee.ImageCollection('USDA/NAIP/DOQQ') \\\n",
        "  .filterBounds(ee.Geometry.Point(-71.08841, 42.39823)) \\\n",
        "  .filterDate('2004-07-01', '2012-12-31') \\\n",
        "  .select(['R', 'G', 'B'])\n",
        "\n",
        "# Temporally composite the images with a maximum value function.\n",
        "composite = naip2004_2012.max()\n",
        "Map.setCenter(-71.12532, 42.3712, 12)\n",
        "Map.addLayer(composite, {}, 'max value composite')\n",
        "\n",
        "\n",
        "# Load four 2012 NAIP quarter quads, different locations.\n",
        "naip2012 = ee.ImageCollection('USDA/NAIP/DOQQ') \\\n",
        "  .filterBounds(ee.Geometry.Rectangle(-71.17965, 42.35125, -71.08824, 42.40584)) \\\n",
        "  .filterDate('2012-01-01', '2012-12-31')\n",
        "\n",
        "# Spatially mosaic the images in the collection and display.\n",
        "mosaic = naip2012.mosaic()\n",
        "Map.setCenter(-71.12532, 42.3712, 12)\n",
        "Map.addLayer(mosaic, {}, 'spatial mosaic')\n",
        "\n",
        "\n",
        "# Load a NAIP quarter quad, display.\n",
        "naip = ee.Image('USDA/NAIP/DOQQ/m_4207148_nw_19_1_20120710')\n",
        "Map.setCenter(-71.0915, 42.3443, 14)\n",
        "Map.addLayer(naip, {}, 'NAIP DOQQ')\n",
        "\n",
        "# Create the NDVI and NDWI spectral indices.\n",
        "ndvi = naip.normalizedDifference(['N', 'R'])\n",
        "ndwi = naip.normalizedDifference(['G', 'N'])\n",
        "\n",
        "# Create some binary images from thresholds on the indices.\n",
        "# This threshold is designed to detect bare land.\n",
        "bare1 = ndvi.lt(0.2).And(ndwi.lt(0.3))\n",
        "# This detects bare land with lower sensitivity. It also detects shadows.\n",
        "bare2 = ndvi.lt(0.2).And(ndwi.lt(0.8))\n",
        "\n",
        "# Define visualization parameters for the spectral indices.\n",
        "ndviViz = {'min': -1, 'max': 1, 'palette': ['FF0000', '00FF00']}\n",
        "ndwiViz = {'min': 0.5, 'max': 1, 'palette': ['00FFFF', '0000FF']}\n",
        "\n",
        "# Mask and mosaic visualization images.  The last layer is on top.\n",
        "mosaic = ee.ImageCollection([\n",
        "  # NDWI > 0.5 is water.  Visualize it with a blue palette.\n",
        "  ndwi.updateMask(ndwi.gte(0.5)).visualize(**ndwiViz),\n",
        "  # NDVI > 0.2 is vegetation.  Visualize it with a green palette.\n",
        "  ndvi.updateMask(ndvi.gte(0.2)).visualize(**ndviViz),\n",
        "  # Visualize bare areas with shadow (bare2 but not bare1) as gray.\n",
        "  bare2.updateMask(bare2.And(bare1.Not())).visualize(**{'palette': ['AAAAAA']}),\n",
        "  # Visualize the other bare areas as white.\n",
        "  bare1.updateMask(bare1).visualize(**{'palette': ['FFFFFF']}),\n",
        "]).mosaic()\n",
        "Map.addLayer(mosaic, {}, 'Visualization mosaic')\n",
        "\n",
        "\n",
        "\n",
        "# # This function masks clouds in Landsat 8 imagery.\n",
        "# maskClouds = function(image) {\n",
        "#   scored = ee.Algorithms.Landsat.simpleCloudScore(image)\n",
        "#   return image.updateMask(scored.select(['cloud']).lt(20))\n",
        "# }\n",
        "\n",
        "# # This function masks clouds and adds quality bands to Landsat 8 images.\n",
        "# addQualityBands = function(image) {\n",
        "#   return maskClouds(image)\n",
        "#     # NDVI \\\n",
        "#     .addBands(image.normalizedDifference(['B5', 'B4']))\n",
        "#     # time in days \\\n",
        "#     .addBands(image.metadata('system:time_start'))\n",
        "# }\n",
        "\n",
        "# # Load a 2014 Landsat 8 ImageCollection.\n",
        "# # Map the cloud masking and quality band function over the collection.\n",
        "# collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\\n",
        "#   .filterDate('2014-06-01', '2014-12-31') \\\n",
        "#   .map(addQualityBands)\n",
        "\n",
        "# # Create a cloud-free, most recent value composite.\n",
        "# recentValueComposite = collection.qualityMosaic('system:time_start')\n",
        "\n",
        "# # Create a greenest pixel composite.\n",
        "# greenestPixelComposite = collection.qualityMosaic('nd')\n",
        "\n",
        "# # Display the results.\n",
        "# Map.setCenter(-122.374, 37.8239, 12) # San Francisco Bay\n",
        "# vizParams = {'bands': ['B5', 'B4', 'B3'], 'min': 0, 'max': 0.4}\n",
        "# Map.addLayer(recentValueComposite, vizParams, 'recent value composite')\n",
        "# Map.addLayer(greenestPixelComposite, vizParams, 'greenest pixel composite')\n",
        "\n",
        "# # Compare to a cloudy image in the collection.\n",
        "# cloudy = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140825')\n",
        "# Map.addLayer(cloudy, vizParams, 'cloudy')\n",
        "\n"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Display Earth Engine data layers "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    }
  ],
  "metadata": {
    "anaconda-cloud": {},
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.1"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 1
}